package com.lbh.graphics;

import com.alibaba.fastjson.annotation.JSONField;
import com.jogamp.opengl.GL2;

import java.util.ArrayList;
import java.util.List;

/***
 * project:JRuntime
 * package:com.lbh.graphics
 *
 * @author user:lenovo QQ:1601078366
 * @date 2021/10/21 23:01
 * @version V1.0
 */
public class GLProgram {

    @JSONField(serialize = false, deserialize = false)
    int program;
    @JSONField(name = "shaders")
    public List<GLShader> shaders;

    public GLProgram(int program){
        this.program = program;
    }

    public GLProgram(GL2 gl){
        program = gl.glCreateProgram();
        shaders = new ArrayList<>();
    }

    public void attachShader(GL2 gl, int stage, String source){
        attachShader(gl, new GLShader(gl, stage, source));
    }

    public void attachShader(GL2 gl, GLShader shader){
        gl.glAttachShader(program, shader.shader);
        shaders.add(shader);
    }

    public int get(){
        return program;
    }

    public void link(GL2 gl){
        gl.glLinkProgram(program);
        GLUtils.printProgramLog(gl, program);
    }

    public int getUniform(GL2 gl, String s){
        return gl.glGetUniformLocation(program, s);
    }

    public void enable(GL2 gl){
        gl.glUseProgram(program);
    }

    public void disable(GL2 gl){
        gl.glUseProgram(0);
    }

    public void delete(GL2 gl){
        if (program == 0){
            return;
        }
        for (GLShader shader : shaders) {
            gl.glDetachShader(program, shader.shader);
            shader.delete(gl);
        }
        gl.glDeleteProgram(program);
    }
}
